import { Form, Input, Button, Checkbox, Icon } from "tea-component";
import { debounce } from 'lodash';
import React, { useState } from "react";
import { Form as FinalForm, Field } from "react-final-form";
import { getStatus } from "../../../utils/getStatus";
import useAsyncRetryFunc from "../../../utils/react-use/useAsyncRetryFunc";
import { getFriendList, getGroupMemberList } from "../../../api";
import { AvatarWithProfile } from "../../../components/avatarWithProfile";
import "./divider.scss";


const validateValue = async (value: string,label: string) => {
  if (!value) {
    return `还没有选择用户`;
  }
};

export interface FormValue {
  UID: [string];
}

interface Props {
  groupId: string;
  onSubmit: (formValue: FormValue) => Promise<void>;
  onSuccess?: () => void;
  onError?: () => void;
  onClose?: () => void;
}

export const AddGroupMemberForm = (props: Props): JSX.Element => {
  const {groupId, onSubmit, onSuccess, onError } = props;
  const { value, loading, retry } = useAsyncRetryFunc(async () => {
    const frends= await getFriendList();
    setResults(frends);
    const userIds = frends.reduce((pre,cur)=>{
        const userid = cur.friend_profile_identifier;
        if(userid && pre.indexOf(userid)<0){
            pre.push(userid);
        }
        return pre;
    }, []);
    const val= await getGroupMemberList({
        groupId,
        nextSeq: 0,
        userIds
    });
    setUserList(val?.group_get_memeber_info_list_result_info_array||[])
    return frends;
  }, []);
  const friendList = value || [];
  const [results,setResults] = useState([]);
    // 获取群成员列表
  const [userList,setUserList] =useState([]);


  // eslint-disable-next-line
  const _handlerSubmit = async (formValue: FormValue) => {
    try {
      await onSubmit(formValue);
      onSuccess?.();
    } catch (error) {
      onError?.();
    }
  };
  const _checkInGround =  (uid:string)=>{
    const ret = userList.find((ele:any)=>ele.group_member_info_identifier == uid );
    return ret;
  };
  const setValue = (value) => {
      setResults(friendList.filter((item:any)=>{
        return item.friend_profile_remark.indexOf(value)!=-1||item.friend_profile_user_profile.user_profile_nick_name.indexOf(value)!=-1
      }));
  }
  const handleInoputOnchange = debounce(setValue, 500);

  return (
    <FinalForm onSubmit={_handlerSubmit} initialValuesEqual={() => true} initialValues={{}}>
      {({ handleSubmit, submitting, validating }) => {
        return (
          <form onSubmit={handleSubmit}>
            <Form.Title>选择用户加入群聊</Form.Title>
            <Form layout="fixed" hideLabel={true} style={{ width: "100%" }}>
            <Field name="UID" disabled={submitting}  validateOnBlur validateFields={[]}
              validate={(value) => validateValue(value , '用户ID')}>
                {({ input, meta }) => (
                  <Form.Item  required  label="选择用户"  status={getStatus(meta, validating)}  style={{height:"450px",display:"flex",overflowY:"scroll"}}
                    message={ getStatus(meta, validating) === "error" && meta.error }>
                    <section className="search-message__input-area" style={{padding:"0",marginBottom:"10px"}}>
                        <Icon className="search-message__input-area--icon" type="search" />
                        <Input className="search-message__input-area--input" type="search" placeholder="查找好友" onChange={handleInoputOnchange}/>
                    </section>
                    {
                        <Checkbox.Group  {...input}  layout="column">
                          {results.map( (item:any) =>{
                            const profile = {
                                userId: item.friend_profile_user_profile.user_profile_identifier,
                                nickName: item.friend_profile_remark||item.friend_profile_user_profile.user_profile_nick_name,
                                faceUrl: item.friend_profile_user_profile.user_profile_face_url,
                                gender: item.friend_profile_user_profile.user_profile_gender,
                                role: item.friend_profile_user_profile.user_profile_role,
                            }
                            //console.log(profile);
                            return(
                            <Checkbox name={item.friend_profile_identifier} disabled={_checkInGround(item.friend_profile_user_profile.user_profile_identifier)}>
                              <AvatarWithProfile profile={profile} isNotTouch={false} />
                              <div><span className="item-left__info--name">{profile.nickName || profile.userId}</span></div>
                            </Checkbox>
                            ) 
                          })}
   
                        </Checkbox.Group>
                        /* <Input {...input} placeholder="请输入用户UID" size="full" disabled={submitting}/> */
                      }
                  </Form.Item>
                )}
              </Field> 
            </Form>
            <Form.Action>
              <Button style={{borderRadius: '4px'}} type="primary" htmlType="submit" loading={submitting}>
                确认
              </Button>
            </Form.Action>
          </form>
        );
      }}
    </FinalForm>
  );
};

